//
//  LoginViewController.m
//  beautyLamp
//
//  Created by Tam Kwok To Michael on 2017/8/8.
//  Copyright © 2017年 Tam Kwok To Michael. All rights reserved.
//

#import "LoginViewController.h"
#import "BLHeader.h"
#import <AVFoundation/AVFoundation.h>
#import "PrivacyViewController.h"
#import "RegisterViewController.h"
#import "GuideViewController.h"
#import <WXApi.h>
#import "AccountLoginViewController.h"
#import <Masonry.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "AppDelegate.h"
#import <WeiboSDK.h>
#import "LoginNet.h"
#import <MBProgressHUD.h>
#import "HomeViewController.h"
#import "BLNavigationController.h"
#import "ChoiceLoginWayView.h"

@interface LoginViewController ()<TencentSessionDelegate,ChoiceLoginWayViewDelegate>

@property (nonatomic, strong) AVPlayer *player;

@property (weak, nonatomic) IBOutlet UILabel *privacyLabel;
@property (weak, nonatomic) IBOutlet UILabel *registerAccount;
@property (nonatomic, strong) UIView *guide;
@property (nonatomic, strong) UIButton *jump;

@property (nonatomic, strong) TencentOAuth *tencentOAuth;
@property (nonatomic, strong) NSMutableArray *permissionArray;   //权限列表
@property (weak, nonatomic) IBOutlet UIView *LoginOutView;

@end

@implementation LoginViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //去掉透明后导航栏下边的黑边
    //[self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    [self.navigationController.navigationBar setHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //如果不想让其他页面的导航栏变为透明 需要重置
    [self.navigationController.navigationBar setHidden:NO];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}


- (void) setupUI {
//    先判断是不是第一次使用app
//    NSString *first =  [[NSUserDefaults standardUserDefaults] objectForKey:isFirst];
//    if(!first || first.length == 0) {
//        GuideViewController *guideController = [[GuideViewController alloc] init];
//        self.guide = guideController.view;
//        [self.view addSubview:self.guide];
//        [self addChildViewController:guideController];
//        __weak typeof (self) weakSelf = self;
//        [self.guide mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.left.right.bottom.equalTo(weakSelf.view);
//        }];
//
//        UIButton *jump = [[UIButton alloc] initWithFrame:CGRectMake(KScreenWidth - 100, 40, 80, 40)];
//        [jump setTitle:@"跳过" forState:UIControlStateNormal];
//        [jump setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [jump addTarget:self action:@selector(jump2Login) forControlEvents:UIControlEventTouchUpInside];
//        self.jump = jump;
//        [self.view addSubview:self.jump];
//        [[NSUserDefaults standardUserDefaults] setObject:isFirst forKey:isFirst];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//    }
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"登录即代表你同意亿诚服务条款和隐私条款" ];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.7] range:NSMakeRange(0,8)];
    
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.85] range:NSMakeRange(8, 11)];
     [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(8, 11)];
    self.privacyLabel.attributedText = str;
    
    self.privacyLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *privacyTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toPrivacyController)];
    [self.privacyLabel addGestureRecognizer:privacyTap];

    NSMutableAttributedString *registerStr = [[NSMutableAttributedString alloc] initWithString:@"注册账号"];
    [registerStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, 4)];
    self.registerAccount.attributedText = registerStr;
    
    UITapGestureRecognizer *registerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toRegisterController)];
    self.registerAccount.userInteractionEnabled = YES;
    [self.registerAccount addGestureRecognizer:registerTap];
    
    [self creatLoginWayButton];
}

#pragma mark 动态创建登录按钮
- (void)creatLoginWayButton {
    BOOL isInstallWX = [WXApi isWXAppInstalled];
    NSInteger index = isInstallWX ? 4 : 3;
    NSArray *icon;
    NSArray *title;
    if (isInstallWX) {
        icon = @[@"whiteAnt", @"login_wx", @"login_wb", @"cm_login_qq"];
        title = @[@"账号登录", @"微信", @"微博", @"QQ"];
    }else {
        icon = @[@"whiteAnt", @"login_wb", @"cm_login_qq"];
        title = @[@"账号登录", @"微博", @"QQ"];
    }
    CGFloat width = KScreenWidth / index;
    for (int i = 0 ; i < index; i++) {
        ChoiceLoginWayView *loginWay = [ChoiceLoginWayView choiceLoginWayView];
        loginWay.frame = CGRectMake(i * width, 0, width / 2, 60);
        loginWay.title = title[i];
        loginWay.icon = icon[i];
        [self.LoginOutView addSubview:loginWay];
        loginWay.delegate = self;
    }
}

- (void)toLogin:(NSString *)funTitle {;
    SEL fun = NSSelectorFromString(funTitle);
    //用指针的方式 消除警告
    IMP imp = [self methodForSelector:fun];
    void (*func)(id, SEL) = (void *)imp;
    func(self, fun);
  //  [self performSelector:fun];
}

- (void)jump2Login {
    __weak typeof (self) weakSelf = self;
    [self.guide mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view.mas_left);
        make.size.equalTo(weakSelf.view);
    }];
    [UIView animateWithDuration:0.3 animations:^{
        [weakSelf.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        [weakSelf.guide removeFromSuperview];
        [weakSelf.jump removeFromSuperview];
    }];
}


# pragma mark 注册
- (void)toRegisterController {
    RegisterViewController *pController = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:pController animated:YES];
}

# pragma mark 隐私
- (void)toPrivacyController {
    PrivacyViewController *pController = [[PrivacyViewController alloc] init];
    [self.navigationController pushViewController:pController animated:YES];
    
}


# pragma mark 账号登录
- (void)whiteAnt {
    AccountLoginViewController *controller = [[AccountLoginViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}


# pragma mark 微信登录
-(void)login_wx {
    //构造SendAuthReq结构体
    SendAuthReq* req =[[SendAuthReq alloc ] init];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"beautyLamp" ;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req];
}

# pragma mark 微博登录
- (void)login_wb {
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = @"https://api.weibo.com/oauth2/default.html";
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"ViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
}

# pragma mark QQ登录
- (void)cm_login_qq {
   // _permissionArray = [NSMutableArray arrayWithObjects: kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,nil];
    //登录操作
    [self.tencentOAuth authorize:self.permissionArray];
}

/**
 * 登录成功后的回调
 */
- (void)tencentDidLogin{
    /** Access Token凭证，用于后续访问各开放接口 */
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    if (_tencentOAuth.accessToken) {
        //获取用户信息。 调用这个方法后，qq的sdk会自动调用
        //- (void)getUserInfoResponse:(APIResponse*) response
        //这个方法就是 用户信息的回调方法。
        [LoginNet QQLoginToken:_tencentOAuth.accessToken openID:_tencentOAuth.openId completer:^(id resultObject, NSError *error) {
            if(resultObject) {
                [hud hideAnimated:YES];
                [[NSUserDefaults standardUserDefaults] setObject:Logined forKey:Logined];
                //self.window.rootViewController = [[BLTabViewController alloc] init];
                [UIApplication sharedApplication].delegate.window.rootViewController = [[BLNavigationController alloc] initWithRootViewController:[[HomeViewController alloc] init]];
            }else {
                hud.label.text = @"登录失败！";
                hud.mode = MBProgressHUDModeText;
                [hud hideAnimated:YES afterDelay:2];
            }
        }];
       // [_tencentOAuth getUserInfo];
    }
//    }else{
//        NSLog(@"accessToken 没有获取成功");
//    }
}


- (void)getUserInfoResponse:(APIResponse *)response {
    //NSLog(@"%@",response.jsonResponse);
}

/**
 * 登录失败后的回调
 * \param cancelled 代表用户是否主动退出登录
 */
- (void)tencentDidNotLogin:(BOOL)cancelled{
    if (cancelled) {
       // NSLog(@" 用户点击取消按键,主动退出登录");
    }else{
        //NSLog(@"其他原因， 导致登录失败");
    }
}

/**
 * 登录时网络有问题的回调
 */
- (void)tencentDidNotNetWork{
    //NSLog(@"没有网络了， 怎么登录成功呢");
}

- (TencentOAuth *)tencentOAuth {
    if (_tencentOAuth == nil) {
        _tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQ_APP_ID andDelegate:self];
    }
    return _tencentOAuth;
}

- (NSMutableArray *)permissionArray {
    if (_permissionArray == nil) {
        _permissionArray = [NSMutableArray arrayWithObjects: kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,nil];
    }
    return _permissionArray;
}

- (void)dealloc {
   // NSLog(@"llh login controller dealloc");
}

@end
